﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text;

namespace AOuSuisJeWP7
{
    public partial class Register : PhoneApplicationPage
    {
        private List<ValidationError> validationErrors;
        private ValidationError credentialError;
        UserLogin userLogin;

        public Register()
        {
            InitializeComponent();
            userLogin = ((App)Application.Current).userLogin;
            validationErrors = new List<ValidationError>();
            this.DataContext = userLogin;
        }
        private UserLogin registerUser(UserLogin userToRegister)
        {
            return userToRegister;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Login.xaml", UriKind.Relative));
        }

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            if (EmailTextBox.Text.Length > 0)
            {
                registerUser(EmailTextBox.Text, PasswordTextBox.Password);
            }
        }

        private bool registerUser(string email, string password)
        {
            RegistrationService.RegisterServiceClient rsc = new RegistrationService.RegisterServiceClient();
            rsc.CreateUserCompleted += new EventHandler<RegistrationService.CreateUserCompletedEventArgs>(rsc_CreateUserCompleted);
            rsc.CreateUserAsync(EmailTextBox.Text, PasswordTextBox.Password);
            return true;
        }

        void rsc_CreateUserCompleted(object sender, RegistrationService.CreateUserCompletedEventArgs e)
        {
            ValidationSummary.Text = e.Result;
            if (e.Result == "User created")
            {
                userLogin.IsAuthenticate = true;
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
        }

        private void displayErrors()
        {
            StringBuilder errors = new StringBuilder();
            foreach (ValidationError ve in validationErrors)
            {
                errors.AppendLine(ve.ErrorContent.ToString());
            }
            ValidationSummary.Text = errors.ToString();
        }
    }
}